package com.kui.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kui.entity.Files;
import com.kui.util.DBHelp;
import com.kui.util.RowMapper;

public class FilesDao {
	
	DBHelp<Files> db = new DBHelp<Files>();
	
	private class FilesRowMapper implements RowMapper<Files>{

		public Files mapperRow(ResultSet rs) throws SQLException {
			Files f = new Files();
			f.setId(rs.getString("id"));
			f.setName(rs.getString("name"));
			f.setDownname(rs.getString("downname"));
			f.setSize(rs.getInt("size"));
			f.setCreatetime(rs.getString("createtime"));
			f.setType(rs.getString("type"));
			f.setT_folder_id(rs.getString("t_folder_id"));
			f.setT_user_id(rs.getString("t_user_id"));
			f.setT_user_name(rs.getString("t_user_name"));
			return f;
		}
		
	}

	public List<Files> findAllByFolderId(String folderid) {
		String sql = "SELECT t_file.id,name,downname,size,createtime,type,t_folder_id,t_user_id,t_user.username AS t_user_name FROM t_file LEFT JOIN t_user ON t_user_id = t_user.id WHERE t_folder_id = ?";
		return db.executeQueryForList(sql, new FilesRowMapper(), folderid);
	}

	public void save(Files f) {
		String sql = "INSERT INTO t_file(id,name,downname,size,createtime,type,t_folder_id,t_user_id) VALUES(?,?,?,?,?,?,?,?)";
		db.executeSQL(sql, f.getId(),f.getName(),f.getDownname(),f.getSize(),f.getCreatetime(),f.getType(),f.getT_folder_id(),f.getT_user_id());
		
	}

	public Files findByDownname(String filename) {
		String sql = "SELECT id,name,downname,size,createtime,type,t_folder_id,t_user_id,t_user_id AS t_user_name FROM t_file WHERE downname = ?";
		return db.executeQueryForObject(sql, new FilesRowMapper(), filename);
	}

	public Files findByIdAndUserId(String fileid, String id) {

		String sql = "SELECT id,name,downname,size,createtime,type,t_folder_id,t_user_id,t_user_id AS t_user_name FROM t_file WHERE id = ? AND t_user_id = ?";
		return db.executeQueryForObject(sql, new FilesRowMapper(), fileid,id);
	}

	public void delById(String fileid) {
		String sql = "DELETE FROM t_file WHERE id = ?";
		db.executeSQL(sql, fileid);
		
	}

	public Files findById(String fileid) {
		String sql = "SELECT id,name,downname,size,createtime,type,t_folder_id,t_user_id,t_user_id AS t_user_name FROM t_file WHERE id = ?";
		return db.executeQueryForObject(sql, new FilesRowMapper(), fileid);
	}

	

}
